<template>
  <view class="edit-info-container">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-back" @click="navigateBack">
      </view>
      <text class="nav-title">编辑个人信息</text>
      <view class="nav-save" @click="saveInfo">
        <text class="save-text">保存</text>
      </view>
    </view>

    <!-- 加载中提示 -->
    <view class="loading" v-if="isLoading">
      <text class="loading-icon">⏳</text>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-area" v-else>
      <!-- 头像上传 -->
      <view class="avatar-upload">
        <image 
          :src="formData.avatar || '/static/default-avatar.png'" 
          class="avatar-img"
          mode="aspectFill"
          @error="handleAvatarError"
        ></image>
        <view class="upload-btn" @click="chooseAvatar">
          <text class="upload-text">更换头像</text>
        </view>
      </view>

      <!-- 基础信息表单（姓名、电话、邮箱、简介） -->
      <view class="form-group">
        <view class="form-item">
          <text class="label">用户姓名 <text class="required">*</text></text>
          <input 
            class="input" 
            type="text" 
            v-model="formData.userName" 
            placeholder="请输入姓名"
          />
        </view>

        <view class="form-item">
          <text class="label">联系电话 <text class="required">*</text></text>
          <input 
            class="input" 
            type="number" 
            v-model="formData.phone" 
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>

        <view class="form-item">
          <text class="label">邮箱 <text class="required">*</text></text>
          <input 
            class="input" 
            type="text" 
            v-model="formData.email" 
            placeholder="请输入邮箱"
          />
        </view>

        <view class="form-item">
          <text class="label">个人简介</text>
          <textarea 
            class="textarea" 
            v-model="formData.introduction" 
            placeholder="请输入个人简介（选填）"
            auto-height
            maxlength="200"
          ></textarea>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/api/request.js';

export default {
  data() {
    return {
      formData: {          // 表单数据（与SysUserDTO字段匹配）
        id: '',            // 系统用户ID（必填，后端用于定位用户）
        userName: '',      // 用户名（与SysUserDTO.userName对应）
        phone: '',         // 电话（与SysUserDTO.phone对应）
        email: '',         // 邮箱（与SysUserDTO.email对应）
        introduction: '',  // 个人简介
        avatar: ''         // 头像地址
      },
      isLoading: true,
      tempAvatarPath: ''
    };
  },
  onLoad() {
    this.initFormData();  // 页面加载时初始化表单数据
  },
  methods: {
    /**
     * 返回上一页
     */
    navigateBack() {
      uni.navigateBack();
    },

    /**
     * 初始化表单：从登录缓存读取系统用户信息
     */
    initFormData() {
      const userInfo = uni.getStorageSync('userInfo') || {}; 
      // 关键：确保表单ID与系统用户ID一致（SysUserDTO的id字段）
      this.formData = {
        id: userInfo.id || '',  // 系统用户ID（必须传递给后端）
        userName: userInfo.userName || userInfo.user_name || '', // 兼容不同命名格式
        phone: userInfo.phone || '',
        email: userInfo.email || '',
        introduction: userInfo.introduction || '',
        avatar: userInfo.avatar || ''
      };
      this.isLoading = false;
    },

    /**
     * 头像加载失败容错
     */
    handleAvatarError() {
      this.formData.avatar = '/static/default-avatar.png';
    },

    /**
     * 选择/更换头像
     */
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.tempAvatarPath = tempFilePath;
          this.formData.avatar = tempFilePath;
          this.uploadAvatar(tempFilePath); // 选择后立即上传
        }
      });
    },

    /**
     * 上传头像到服务器（假设系统用户头像接口路径）
     */
    uploadAvatar(tempPath) {
      const userId = this.formData.id; // 使用系统用户ID
      if (!userId) {
        uni.showToast({ title: '用户ID不存在，无法上传头像', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '上传中...' });
      uni.uploadFile({
        url: 'http://localhost:6013/order-client/cms/sysUser/uploadAvatar', // 系统用户头像接口
        filePath: tempPath,
        name: 'file',
        formData: { userId }, // 传递系统用户ID
        header: {
          'Token': uni.getStorageSync('token') // 携带登录令牌
        },
        success: (uploadRes) => {
          uni.hideLoading();
          try {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 0 && data.data) {
              this.formData.avatar = data.data.avatarUrl;
              uni.showToast({ title: '头像上传成功', icon: 'success' });
              // 同步更新缓存头像
              const userInfo = uni.getStorageSync('userInfo') || {};
              userInfo.avatar = data.data.avatarUrl;
              uni.setStorageSync('userInfo', userInfo);
            } else {
              uni.showToast({ title: data.msg || '头像上传失败', icon: 'none' });
            }
          } catch (e) {
            uni.showToast({ title: '上传失败，解析错误', icon: 'none' });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: '网络错误，上传失败', icon: 'none' });
        }
      });
    },

    /**
     * 保存个人信息：调用系统用户更新接口（核心修改点）
     */
    saveInfo() {
      // 1. 表单校验
      if (!this.formData.userName.trim()) {
        uni.showToast({ title: '用户姓名不能为空', icon: 'none' });
        return;
      }
      if (!this.formData.phone.trim() || !/^1\d{10}$/.test(this.formData.phone.trim())) {
        uni.showToast({ title: '请输入11位有效手机号', icon: 'none' });
        return;
      }
      if (!this.formData.email.trim()) {
        uni.showToast({ title: '邮箱不能为空', icon: 'none' });
        return;
      }
      // 关键：验证系统用户ID存在（后端SysUserController需要id定位用户）
      if (!this.formData.id) {
        uni.showToast({ title: '用户身份无效，请重新登录', icon: 'none' });
        return;
      }

      // 2. 调用系统用户更新接口：/cms/sysUser/update（与后端路径匹配）
      uni.showLoading({ title: '保存中...' });
      request.post(
        '/cms/sysUser/update', // 核心修改：系统用户更新接口路径
        this.formData,         // 传递包含id的完整表单数据
        true                   // 保持原有请求配置（如携带Token）
      )
      .then(res => {
        uni.hideLoading();
        uni.showToast({ title: '个人信息保存成功', icon: 'success' });
        // 3. 同步更新登录缓存（确保其他页面数据最新）
        const userInfo = uni.getStorageSync('userInfo') || {};
        userInfo.userName = this.formData.userName;
        userInfo.phone = this.formData.phone;
        userInfo.email = this.formData.email;
        userInfo.introduction = this.formData.introduction;
        uni.setStorageSync('userInfo', userInfo);
        // 4. 延迟返回上一页
        setTimeout(() => uni.navigateBack(), 1500);
      })
      .catch(err => {
        uni.hideLoading();
        uni.showToast({ title: err.msg || '保存失败，请重试', icon: 'none' });
      });
    }
  }
};
</script>

<style scoped>
.edit-info-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.top-nav {
  height: 88rpx;
  background-color: #5555ff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  justify-content: space-between;
}
.nav-back {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.back-icon {
  font-size: 36rpx;
  color: #fff;
}
.nav-title {
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
}
.nav-save {
  padding: 8rpx 20rpx;
  background-color: #fff;
  border-radius: 6rpx;
}
.save-text {
  font-size: 28rpx;
  color: #5555ff;
  font-weight: 500;
}

.loading {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.loading-icon {
  font-size: 60rpx;
  color: #5555ff;
  margin-bottom: 20rpx;
}
.loading-text {
  font-size: 28rpx;
  color: #666;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32rpx 0;
  background-color: #fff;
  margin-bottom: 16rpx;
}
.avatar-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  margin-bottom: 24rpx;
  border: 2rpx solid #eee;
  background-color: #eee;
}
.upload-btn {
  padding: 12rpx 36rpx;
  border-radius: 24rpx;
  background-color: #f0f0f0;
  font-size: 26rpx;
  color: #666;
  cursor: pointer;
}

.form-area {
  flex: 1;
  background-color: #fff;
  padding: 24rpx;
  overflow-y: auto;
}
.form-group {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}
.form-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}
.label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
.required {
  color: #ff4d4f;
  font-size: 28rpx;
}
.input {
  height: 80rpx;
  line-height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 6rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #666;
}
.textarea {
  min-height: 160rpx;
  border: 1rpx solid #eee;
  border-radius: 6rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}
</style>
